<?php
declare (strict_types = 1);

namespace app\admin\controller\user;

use app\admin\BaseController;
use app\common\model\user\Permission as PermissionModel;
use think\facade\Log;
use think\exception\ValidateException;
use think\Exception;
use app\common\validate\Permission as PermissionValidate;

class Permission extends BaseController
{
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list','save','saveRoute','update','delete','batchDel','saveRelate']],
    ];

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view('index');
    }

    public function list(){
        try{
            //获取列表数据
            $data = PermissionModel::getListData($this->ruleWhere());


        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage(),
            ]);
        }

        //成功返回
        return json([
            'code'  => 0,
            'msg'=> '查询列表成功',
            'count' => $data['count'],
            'data'  => $data['list']
        ]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function createRoute()
    {
        return view('create-route',[
            'added' => PermissionModel::getAdded(),
            'notAdded' => PermissionModel::getNotAdded()
        ]);
    }

    /**
     * 编辑路由
     */
    public function saveRoute(){
        try{
            $data = request()->only(['permissions']);
            if ($data){
                validate(['permissions'=>'array'])
                    ->check($data);
            }else{
                $data['permissions'] = [];
            }


            if (!PermissionModel::saveRoute($data['permissions']))
                throw new Exception('操作失败');

        }catch (ValidateException $e){
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        return json(['code'=>0,'msg'=>'操作成功']);
    }



    /**
     * 保存新建的资源
     *
     * @return \think\Response
     */
    public function save()
    {
        return $this->store($this->getModel(PermissionModel::class), '创建权限成功.', '创建权限失败.');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function relate(int $id)
    {
        return view('relate',[
            'model' => $this->getModel(PermissionModel::class, $id),
            'allRoute' => PermissionModel::getRouteList(),
            'related' => implode(',',PermissionModel::getRelated($id))

        ]);
    }


    /**
     * #保存关联数据
     * @return \think\response\Json
     */
    public function saveRelate(int $id)
    {
        try{
            //先获取角色模型
            $model = $this->getModel(PermissionModel::class, $id);

            //验证数据
            $data = request()->only(['routes']);
            if(empty($data)){
                $routes = [];
            }else{
                validate(['routes'=>'array'])->check($data);
                $routes = $data['routes'];
            }


            if( !$model->updateRelate($routes) )
                throw new Exception('授权失败');


        } catch (ValidateException $e) {

            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){

            //系统错误
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }

        //添加成功
        return json(['code'=>0,'msg'=>'授权成功']);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @return \think\Response
     */
    public function edit(int $id)
    {
        return view('edit',[
            'model' => $this->getModel(PermissionModel::class, $id)
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(int $id)
    {
        return $this->store($this->getModel(PermissionModel::class,$id), '修改权限成功.', '修改权限失败.');
    }

    /**
     * 删除指定资源
     *
     */
    public function delete(int $id)
    {
        //获取模型
        $model = $this->getModel(PermissionModel::class,$id);
        try{
            if ($model->delete() === false){
                throw new Exception('删除权限失败.');
            }

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        //删除成功
        return json(['code'=>0,'msg'=>'删除权限成功']);
    }

    //批量删除
    public function batchDel()
    {
        try{
            $ids = explode(',', trim(input('ids/s'),','));

            if ($this->batchRule(PermissionModel::class, (array) $ids) &&
                PermissionModel::destroy($ids) === false
            ){
                throw new Exception('批量删除权限失败.');
            }

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        //删除成功
        return json(['code'=>0,'msg'=>'批量删除权限成功']);
    }


    /**
     * 处理post提交
     * @param UserModel $model
     * @param string $okMsg
     * @param string $errMsg
     * @return \think\response\Json
     */
    private function store(PermissionModel $model, string $okMsg, string $errMsg){

        try{
            //验证数据
            $data = request()->only(['name','desc','rule']);
            if (!$model->isExists()){
                $data = array_merge($data, ['type'=>PermissionModel::TYPE_ROLE]);
            }

            validate(PermissionValidate::class)->check(array_merge($data, ['id'=>$model->id]));


            if( !$model->save($data) )
                throw new Exception($errMsg);


        } catch (ValidateException $e) {

            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){

            //系统错误
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }

        //添加成功
        return json(['code'=>0,'msg'=>$okMsg]);
    }
}
